﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YJKView;

namespace YJKAxisAndEdit
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class CmdCreateGridByWall : IExternalCommand
	{
		public Result Execute(ExternalCommandData cmdData, ref string msg, ElementSet elems)
		{
			CmdViewType types = CmdViewType.FloorPlan;
			if (SwitchView.SetUsableView(types, cmdData) != Autodesk.Revit.UI.Result.Succeeded)
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			Transaction transaction = null;
			Result result;
			try
			{
				if (cmdData == null)
				{
					throw new System.ArgumentNullException("commandData");
				}
				WallToGridForm wallToGridForm = new WallToGridForm(cmdData);
				if (wallToGridForm.ShowDialog() != DialogResult.OK)
				{
					result = Autodesk.Revit.UI.Result.Cancelled;
				}
				else
				{
					Document document = cmdData.Application.ActiveUIDocument.Document;
					transaction = new Transaction(document);
					transaction.Start("Create Grid By Wall");
					IList<Reference> list = null;
					Selection selection = cmdData.Application.ActiveUIDocument.Selection;
					try
					{
						list = selection.PickObjects(Autodesk.Revit.UI.Selection.ObjectType.Element, new WallFilter(), "选择墙");
					}
					catch (Exception)
					{
						if (transaction != null && transaction.HasStarted() && !transaction.HasEnded())
						{
							transaction.RollBack();
						}
						return Autodesk.Revit.UI.Result.Failed;
					}
					List<Curve> list2 = new List<Curve>();
					foreach (Reference reference in list)
					{
						Element element = document.GetElement(reference);
						Wall wall = element as Wall;
						if (wall != null)
						{
							Curve curve = (wall.Location as LocationCurve).Curve;
							if (curve.IsBound)
							{
								list2.Add(curve);
							}
						}
					}
					GridCreatorByCurve gridCreatorByCurve = new GridCreatorByCurve(cmdData, wallToGridForm.GetGridType(), wallToGridForm.ExtendLength());
					gridCreatorByCurve.CreateGridByCurves(list2);
					transaction.Commit();
					result = Autodesk.Revit.UI.Result.Succeeded;
				}
			}
			catch (Exception ex)
			{
				msg = ex.Message;
				if (transaction != null && transaction.HasStarted() && !transaction.HasEnded())
				{
					transaction.RollBack();
				}
				result = Autodesk.Revit.UI.Result.Failed;
			}
			return result;
		}
	}
}
